//
//  NetworkTools.swift
//  测试封装网络方法 Swift
//
//  Created by apple on 15/12/28.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
//第一步要导入框架
import AFNetworking

///HTTP 请求方法的枚举
enum HMRequestMethod: String {

    case GET = "GET"
    case POST = "POST"
}
///网络工具
class NetworkTools: AFHTTPSessionManager {
    
    //MARK: 应用程序信息
    private let appKey = "3135619345"
    private let appSecret = "ca7fd795ee8ab27af2eaec0a9bf79c7f"
    private let redirectUrl = "http://www.baidu.com"
    
    ///网络请求完成回调 类似于OC的typeDefine
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()

 
    //创建单例
    static let sharedTools: NetworkTools = {
    
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    ///返回  token 字典
    
    private var tokenDict: [String: AnyObject]? {
    
        //判断 token 是否有效 
        if let token = UserAccountViewModel.sharedUserAccount.accessToken {
        
            return ["access_token": token]
        }
        return nil
    }

}

//MARK: 用户相关方法
extension NetworkTools {

    ///加载用户信息
    func loadUserInfo(uid: String,  finished: HMRequestCallBack) {
         // 1. 获取 token 字典
        guard var params = tokenDict else {
            // 如果字典为 nil，通知调用方，token 无效

            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        // 2. 处理网络参数
        let urlString = "https://api.weibo.com/2/users/show.json"
 
        params["uid"] = uid
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    
    }
}

//MARK: OAuth 相关方法

extension NetworkTools {

    ///OAuth 授权 URL 
    /// -see [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    ///加载 AccessToken
    func loadAccessToken(code: String, finished:HMRequestCallBack) {
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)

    }
}

//MARK: 封装AFN网络方法
extension NetworkTools {

   private func request(methoud: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        
        if methoud == HMRequestMethod.GET {
        
            GET(URLString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                

                finished(result: result, error: nil)
                
                }) { (_, error) -> Void in
                    //错误不要提供给用户  但是一定要输出
                    print(error)
                    finished(result: nil, error: error)
                    
            }
        } else if methoud == HMRequestMethod.POST {
        
            POST(URLString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                
                finished(result: result, error: nil)
                
                }, failure: { (_, error) -> Void in
                    //错误不要提供给用户  但是一定要输出
                    print(error)
                    finished(result: nil, error: error)
            })
        }
    }
    
}